package com.atom.module.captcha.service.impl;

import com.atom.module.captcha.config.Captcha;
import com.atom.module.captcha.config.CaptchaEnum;
import com.atom.module.captcha.service.CaptchaService;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.awt.image.BufferedImage;

@Service
public class CaptchaServiceImpl implements CaptchaService {

    private final Producer captchaProducer;

    private final Producer captchaProducerMath;

    public CaptchaServiceImpl(@Qualifier("captchaProducer") Producer captchaProducer, @Qualifier("captchaProducerMath") Producer captchaProducerMath) {
        this.captchaProducer = captchaProducer;
        this.captchaProducerMath = captchaProducerMath;
    }

    @Override
    public Captcha getCode(CaptchaEnum captchaEnum) {
        String capStr;
        BufferedImage image;
        // 生成验证码
        if (CaptchaEnum.Math == captchaEnum) {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            image = captchaProducerMath.createImage(capStr);
        } else {
            capStr = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }
        return new Captcha(image, capStr);
    }
}
